package com.util;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class SessionUtil {

    static InputStream is= SessionUtil.class.getResourceAsStream("/SqlMapConfig.xml");
    static SqlSessionFactory factory =new SqlSessionFactoryBuilder().build(is);
    static ThreadLocal<SqlSession> threadLocal=new ThreadLocal<>();
    public static SqlSession getSession(){
        SqlSession session=threadLocal.get();
        if (session==null){
            session=factory.openSession();
            threadLocal.set(session);
        }else {
            try
            {
                session.getConnection();
            }catch (Exception e){
                session=factory.openSession();
                threadLocal.set(session);
            }
        }
        return session;
    }

    public static <T> T getDao(Class c){
        return (T)getSession().getMapper(c);
    }


}